<template>
  <div>
    <!-- <dialog-comp v-if="showDialog" :v-show-dialog.sync="showDialog" @dialogClose="dialogClose" ref="dialog"></dialog-comp> -->
    <modify-dialog-comp v-if="showDialogModify" :show-child-dialog.sync="showDialogModify" ref="dialogmodify" @modifyFlush="flushTable"></modify-dialog-comp>
    <add-dialog-comp v-if="showDialogAdd" :show-child-dialog.sync="showDialogAdd" ref="dialogadd" @addFlush="flushTable"></add-dialog-comp>
    <view-dialog-comp v-if="showDialogView" ref="dialogview" :show-child-dialog-view.sync="showDialogView"></view-dialog-comp>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '8px' }"
    >
      <t-row style="margin-top: 20px;">
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :flex="1">
              <t-form-item label="job名称" name="name">
                <t-input
                  v-model="formData.name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入job名称"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="1.5" class="operation-ad-container">
          <t-button @click="handleCreatChain" theme="primary" :style="{ marginLeft: '8px'}"> 创建job </t-button>
          <t-button @click="handleDeleteChain" variant="base" theme="default" :disabled="!selectedRowKeys.length"> 删除job </t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table
        :data="data"
        :columns="columns"
        rowKey="id"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
      >
      <template #status="row">
        <p class="status" :class="['', 'warning', 'unhealth'][row.con_state]">
              {{ ['健康', '警告', '异常'][row.con_state] }}
            </p>
          <!-- <t-tag v-if="row.status === CASE_STATUS.INIT" theme="danger" variant="light">未执行</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.RUN" theme="warning" variant="light">执行中</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.SUCCESS" theme="warning" variant="light">成功</t-tag>
          <t-tag v-if="row.status === CASE_STATUS.FAIL" theme="success" variant="light">失败</t-tag> -->
      </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="handleClickBuild(slotProps)">运行</a>
          <a class="t-button-link" @click="startBuild(slotProps)">日志</a>
          <a class="t-button-link" @click="handleClickDetail(slotProps)">查看</a>
          <!-- <a class="t-button-link" @click="handleClickModify(slotProps)">编辑</a> -->
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>          
        </template>
      </t-table>
      
      <t-dialog
        header="确认删除当前所选job？"
        :body="confirmBody"
        :visible.sync="confirmVisible"
        @confirm="onConfirmDelete"
        :onCancel="onCancel"
        @deleteFlush="flushTable"
      >
      </t-dialog>
    </div>
    <div>
      <!-- <button @click="startBuild">Start Build</button> -->
      <div v-if="showLog">
        <ul>
          <li v-for="line in logLines" :key="line">{{ line }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script lang="jsx">
// import Vue from 'vue';
// import { prefix } from '@/config/global';
// import Trend from '@/components/trend/index.vue';
// import modifyDialogComp from './ModifyDialogComp.vue';
// import addDialogComp from './AddDialogComp.vue';
import ViewDialogComp from './ViewDialogComp.vue';

// import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon} from 'tdesign-icons-vue';
import {operateChainConn} from '@/api/requestApi';

// import Utils from '../../../utils/util.js';

// import {listChains, getChainsDetail, addChains, modifyChains, delChains} from '@/api/chains/data'

// import { message } from 'tdesign-vue';
import { JENKINS_JOB_LIST } from '@/service/service-detail'


const INITIAL_FORM_DATA = {
  name: '',
};

export default {
  name: 'list-table',
  
  components:{
    // modifyDialogComp,
    // addDialogComp,
    ViewDialogComp,
  },
  inject: ['reload'],
  data() {
    return {
      showLog: false,
      logLines: [],
      showDialogView: false, // 控制查看日志弹窗的现实与隐藏
      formData: {...INITIAL_FORM_DATA},
      data: [],
      resp: {},
      queryData: [],
      selectedRowKeys: [],
      dataLoading: false,
      jenkinsJobList: {...JENKINS_JOB_LIST},
      JENKINS_JOB_LIST,
      // value: 'first',
      columns: [
        { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
        {
          title: 'job名称',
          width: 150,
          ellipsis: true,
          colKey: 'name',
        },
        {
          title: '构建次数数',
          width: 50,
          ellipsis: true,
          colKey: 'build_count',
        },
        {
          title: '最近一次状态',
          width: 50,
          ellipsis: true,
          colKey: 'last_status',
        },
        {
          title: '查看日志',
          width: 150,
          ellipsis: true,
          colKey: 'console_output',
        },
        {
          align: 'left',
          fixed: 'right',
          width: 100,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'index',
      tableLayout: 'auto',
      verticalAlign: 'top',
      showDialogModify: false, // 控制弹窗的现实与隐藏
      showDialogAdd: false, // 控制弹窗的现实与隐藏
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      deleteChainName: '',
    };
  },
  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        // console.log(this.deleteChainName)
        // const { chain_name } = this.deleteChainName;
        // return `${chain_name}的链连接信息将被清空，删除后将无法恢复`;
        return 'job删除后将无法恢复';
      }
      return 'job删除后将无法恢复';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    // this.dataLoading = true;
    this.data = this.JENKINS_JOB_LIST
    // this.pagination = {
    //   ...this.pagination,
    //   total: this.resp.data.length,
    // };
    // this.$request
    //   .get('api/query/jenkins_job_list')
    //   .then((res) => {
    //     console.log(res.data)
    //     if (res.data.code === '000') {
    //       this.$message.success(res.data.msg);
    //       const list = res.data.data;
    //       this.data = list;
    //       console.log('后端数据->', list)
    //       this.pagination = {
    //         ...this.pagination,
    //         total: list.length,
    //       };
    //     } else {
    //       this.$message.error(res.data.msg);
    //     }     
    //   })
    //   .catch((e) => {
    //     this.$message.error('系统异常');
    //     console.log(e)
        
    //   })
    //   .finally(() => {
    //     this.dataLoading = false;
    //   });

  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    onReset() {
      this.formData.name = '';
    },
    onSubmit() {
      this.dataLoading = true;
      const job_name = this.formData.name;
      // const newData = [];
      console.log(job_name)
      this.data = this.data.filter(item => item.name.includes(job_name))
      // for (let i = 0; i < this.data.length; i++){
      //   // if (this.data[i].name === job_name){
      //   if (this.data[i].name.search(job_name)) {
      //     newData.push(this.data[i]);
      //     console.log(newData)
      //     // this.data = this.data[i]
      //   }
      // }
      // this.data = newData;
      this.dataLoading = false;

    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    rehandleSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      console.log(selectedRowKeys);
    },
    handleClickBuild(slotProps) {
      this.chainConn = true;
      console.log(slotProps)
      const viewData = {'build_info':'', 'jenkins_log':''}
      const job_name = slotProps.row.name
      const reqParam = {'job_name': job_name}
      this.$request
        .post('api/run/jenkins_job', reqParam)
        .then((res) => {
          console.log(res)
          if (res.data.code === '000') {
            viewData.jenkins_log = res.data.data
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.showDialogView = true;
      this.$nextTick(()=>{      
        this.$refs.dialogview.init(viewData);
      });
      // this.flushTable();
    },
    addOrUpdateRefresh() {
      console.log("text, row");
    },
    handleClickDetail(slotProps) {
      this.showDialogModify = true;
      this.$nextTick(()=>{
      // 调用的是d子组件里面的init方法传递行数据      
        this.$refs.dialogmodify.init(slotProps.row);
      })
    },
    // handleClickModify(slotProps) {
    //   this.showDialogModify = true;
    //   this.$nextTick(()=>{
    //   // 调用的是d子组件里面的init方法传递行数据      
    //     this.$refs.dialogmodify.init(slotProps.row);
    //   })
    // },
    // 关闭弹窗组件
    dialogClose() {
      this.showDialogModify = true
    },
    handleCreatChain() {
      this.showDialogAdd = true
      // console.log('fff--->',this.formData)
    },
    
    handleClickDelete(slotProps) {
      this.deleteIdx = slotProps.row.id;
      this.deleteChainName = slotProps.row.name;
      console.log("打印下单选",this.deleteIdx,slotProps)
      this.confirmVisible = true;
    },
    handleDeleteChain() {
      const selectedIdx = this.selectedRowKeys
      // console.log("打印下多选",selectedIdx)
      this.confirmVisible = true;

    },
    onConfirmDelete() {
      // 真实业务请发起请求
      let ids = [];
      const reqParam = {"ids": [], "param": {}, "op_type": ''};
      this.confirmVisible = false;
      // console.log("打印下单选deleteIdx",this.deleteIdx)
      if (this.deleteIdx > -1){
        ids.push(this.deleteIdx)
        // console.log("打印下单选ids",ids)
      } else {
        ids = Array.from(Object.values(this.selectedRowKeys), x=>x);
        // ids = Object.values(this.selectedRowKeys)
        // console.log("打印下多选ids",ids)
      }
      this.ids = ids.map(String)
      reqParam.op_type = 0;
      reqParam.ids = this.ids;
      // console.log("提交的表单内容", reqParam);
      if (ids.length > 0) {
        operateChainConn(reqParam)
          .then((res) => {
            if (res.data.code === "000") {
              this.$message.success('链连接删除成功');
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch((e) => {
            this.$message.error('系统异常');
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      }
      this.flushTable();
      this.resetIdx();
    },
    
    handleChangeCreateUser(...args) {
      console.log('change', ...args);
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    closeConn() {
      this.chainConn = false;
    },
    closeLog() {
      this.chainConnLog = false;
    },
    // sleep
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async flushTable(){
      await this.sleep(1000)
      this.reload();
    },
    startBuild(slotProps) {
      this.showLog = true;
      this.logLines = [];
      const job_name = slotProps.row.name;
      // const url = 
      const socket = new WebSocket(`ws://127.0.0.1:18000/get_build_log/${job_name}`);
      socket.onopen = () => {
        console.log("Connected to server.");
      };
      socket.onmessage = (event) => {
        this.logLines.push(event.data);
      };
    },
    // 处理字典
    // mapData(data) {
    //   const mappedData = { ...data };
    //   const sexMap = { '1': '男', '2': '女' };
    //   const typeMap = { '1': '类型1', '2': '类型2', '3': '类型3' };
    //   mappedData.sex = sexMap[data.sex];
    //   mappedData.type = typeMap[data.type];

    //   return mappedData;
    // }
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.form-item-content {
  width: 50%;
}

.selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-s);
    color: var(--td-text-color-secondary);
  }
.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px;
}
</style>
